package com.example.shop_2305.detail

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.Button
import android.widget.EditText
import android.widget.PopupWindow
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.ActionBar.LayoutParams
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.mvvm.BaseViewActivity
import com.example.lib_base.room.AppDataBase
import com.example.lib_base.room.AppDbUtils
import com.example.lib_base.room.MessageEntity
import com.example.shop_2305.R
import com.example.shop_2305.adapter.ImgAdapter
import com.example.shop_2305.adapter.MessageAdapter
import com.example.shop_2305.databinding.ActivityMessageBinding
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import java.text.SimpleDateFormat

@Route(path = "/app/MessageActivity")
class MessageActivity : BaseViewActivity<ActivityMessageBinding>() {
    //展示对应商品的评论  所以需要有一个商品id 作为参数 传过来
    @Autowired
    @JvmField
    var gid = 1

    var imgs = mutableListOf<String>()//用来存储上传的图片
    lateinit var imgAdapter: ImgAdapter

    lateinit var messageAdapter: MessageAdapter
    @SuppressLint("SimpleDateFormat")
    override fun initView() {
        ARouter.getInstance().inject(this)


        messageAdapter = MessageAdapter()
        binding.rvMsg.adapter = messageAdapter
        binding.rvMsg.layoutManager = LinearLayoutManager(this)

        queryMsg()
        //左滑删除
        ItemTouchHelper(object :ItemTouchHelper.Callback(){
            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
                val left = ItemTouchHelper.LEFT
                return makeMovementFlags(0,left)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                //滑动结束后
                val position = viewHolder.layoutPosition//获取当前滑动下标
                AppDbUtils.getAppDb().getMesssageDao().delete(messageAdapter.data[position])

                messageAdapter.data.removeAt(position)
                messageAdapter.notifyItemRemoved(position)//局部刷新
            }
        }).attachToRecyclerView(binding.rvMsg)


        binding.btnMsg.setOnClickListener {

            val popupWindow = PopupWindow()
            popupWindow.width = LayoutParams.MATCH_PARENT
            popupWindow.height = LayoutParams.WRAP_CONTENT
            val view = LayoutInflater.from(this).inflate(R.layout.pop_msg, null)
            //监听et,显示个数 当个数为20时，数量变红
            view.findViewById<EditText>(R.id.et).addTextChangedListener(object:TextWatcher{
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    val tvCount = view.findViewById<TextView>(R.id.tv_count)
                    if (s != null) {
                        tvCount.text = "${s.length}/20"
                        if(s.length==20){
                            tvCount.setTextColor(Color.RED)
                        }else{
                            tvCount.setTextColor(Color.BLACK)
                        }
                    }
                }

                override fun afterTextChanged(s: Editable?) {

                }
            })
            //点击图片上传按钮，选择图片，进行依次展示，不超过3个
            view.findViewById<Button>(R.id.btn_upload).setOnClickListener {
                //怎么判断上传了3个
                if(imgs.size==3){
                    ToastUtils.showLong("最多可以上传3张图片")
                }else{
                    PictureSelector.create(this,200).selectPicture()
                }
            }

            imgAdapter = ImgAdapter()
            val rvImg = view.findViewById<RecyclerView>(R.id.rv_img)
            rvImg.adapter = imgAdapter
            rvImg.layoutManager = GridLayoutManager(this,3)

            popupWindow.setOnDismissListener {
                imgs.clear()
                //图片数据消失，防止不能再添加图片
            }
            //点击保存到数据库中
            view.findViewById<Button>(R.id.btn_send).setOnClickListener {
                val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm")
                val createTime = simpleDateFormat.format(System.currentTimeMillis())
                val messageEntity = MessageEntity(0,gid,view.findViewById<EditText>(R.id.et).text.toString(),SPUtils.getInstance().getString("phone"),5f,createTime,
                    "${if(imgs.size>0) imgs[0] else ""}",//至少选择了一张图片，显示第一张
                    "${if(imgs.size>1) imgs[1] else ""}",//至少选择了二张图片，显示第二张
                    "${if(imgs.size>2) imgs[2] else ""}"//至少选择了三张图片，显示第三张
                    )
                AppDbUtils.getAppDb().getMesssageDao().insert(messageEntity)
                ToastUtils.showLong("发表评论成功")
                popupWindow.dismiss()
                queryMsg()//实时更新
            }


            popupWindow.contentView = view
            popupWindow.isFocusable = true//获取焦点  当文字输入不成功时，添加这项
            popupWindow.isOutsideTouchable = true//点击空白处消失
            popupWindow.showAtLocation(binding.btnMsg,Gravity.BOTTOM,0,0)


        }
    }

    private fun queryMsg() {
        val list = AppDbUtils.getAppDb().getMesssageDao().query(gid)
        messageAdapter.data.clear()
        messageAdapter.data.addAll(list)
        messageAdapter.notifyDataSetChanged()
    }

    override fun initData() {

    }

    override fun getLayout(): Int  = R.layout.activity_message

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==200&&resultCode== RESULT_OK){
            val pictureBean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            imgs.add(pictureBean.path)
            //怎么显示到popupwindow
            imgAdapter.data.clear()
            imgAdapter.data.addAll(imgs)
            imgAdapter.notifyDataSetChanged()
        }
    }

}